<template>
	<view>
		<u-upload ref="uUpload" :action="action" :header="header" :file-list="fileList" :max-size="maxSize"
			:limitType="limitType" :max-count="maxCount" @on-success="onSuccess" @on-remove="onRemove" :multiple="maxCount > 1" />
	</view>
</template>

<script>
	import {
		uploadUrl,
		imageUrl
	} from "@/settings.js";
	const exclude = ['/login', '/captchaImage']; // 排除token验证
	export default {
		name: "ImageUpload",
		props: {
			// 上传数量
			maxCount: {
				type: String,
				default: '6'
			},
			//上传大小
			maxSize: {
				type: String,
				default: '5 * 1024 * 1024'
			},
			limitType: {
				type: Array,
				default: ['png', 'jpg', 'jpeg', 'webp', 'gif']
			},
			value: [String, Object, Array]
		},
		watch: {
			value: {
				handler(val) {
					if (this.fileList.length == 0 && val) {
						// 首先将值转为数组
						const list = Array.isArray(val) ? val : this.value.split(',');
						this.fileList = list.map(item => {
							item = {
								url: this.imageUrl + item
							}
							return item;
						})
					}
				}
			}
		},
		data() {
			return {
				action: uploadUrl,
				header: {
					"Authorization": 'Bearer ' + uni.getStorageSync('token')
				},
				fileList: [],
				inputList: ""
			};
		},
		methods: {
			/**
			 * 图片上传成功时触发
			 * @param {Object} data
			 * @param {Object} index
			 * @param {Object} lists
			 * @param {Object} name
			 */
			onSuccess(data, index, lists, name) {
				if (data.code == 200) {
					this.$emit("imageUpload", this.listToString(lists));
					this.$emit('input', this.listToString(lists))
				}
				this.fileList = lists
				console.log(lists, this.listToString(lists));
			},

			/**
			 * 移除图片时触发
			 * @param {Object} index
			 * @param {Object} lists
			 * @param {Object} name
			 */
			onRemove(index, lists, name) {
				if (lists.length === 0) {
					this.$emit("imageUpload", null);
					this.$emit('input', null)
				} else {
					this.$emit("imageUpload", this.listToString(lists));
					this.$emit('input', this.listToString(lists))
				}
			},

			listToString(lists, separator) {
				let strs = "";
				separator = separator || ",";
				for (let i in lists) {
					let response = lists[i].response;
					if (response) {
						if (response.code == 200) {
							strs += response.fileName + separator;
						}
					} else {
						const arr = lists[i].url.split(this.imageUrl)
						if (arr.length == 2) {
							strs += arr[1] + separator;
						}
					}
				}
				return strs != '' ? strs.substr(0, strs.length - 1) : '';
			}
		}
	}
</script>

<style>

</style>